﻿using Dapper;
using System;
using BCEntity.TMS.WorkingCompany;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.TMS.WorkingCompany
{
    /// <summary>
    /// 劳务公司
    /// </summary>
    public class WorkingCompanyData : IWorkingCompanyData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM workingcompany";
        private const string QUERY = @"SELECT WorkingCompanyId,UpdateTime,EditAdminId,EditAdminName,EnabledManualAssign,ManualAssignWaitTime,CompanyId,CompanyName,
											DepartmentId,DepartmentName,WorkingCompanyName,CreateTime,CreateAdminId,CreateAdminName 
										FROM workingcompany";
        public WorkingCompanyData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查劳务公司是否存在
        public async Task<bool> Exists(long workingCompanyId)
        {
            string sql = string.Format(@"{0} WHERE WorkingCompanyId=?WorkingCompanyId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkingCompanyId", workingCompanyId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加劳务公司
        public async Task<WorkingCompanyEntity> Add(WorkingCompanyEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("workingcompany", new string[] { "CompanyId", "CompanyName", "DepartmentId", "DepartmentName", "WorkingCompanyName", "CreateAdminId", "CreateAdminName" });
            sql = string.Format("{0} {1} WHERE WorkingCompanyId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
            parameters.Add("?DepartmentName", entity.DepartmentName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?WorkingCompanyName", entity.WorkingCompanyName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkingCompanyEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改劳务公司
        public async Task<WorkingCompanyEntity> Update(WorkingCompanyEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("workingcompany", new string[] { "UpdateTime", "EditAdminId", "EditAdminName", "EnabledManualAssign", "ManualAssignWaitTime", "DepartmentId", "DepartmentName", "WorkingCompanyName" }, new string[] { "WorkingCompanyId" });
            sql = string.Format("{0} {1} WHERE WorkingCompanyId=?WorkingCompanyId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkingCompanyId", entity.WorkingCompanyId, DbType.Int64, size: 20);
            parameters.Add("?UpdateTime", entity.UpdateTime, DbType.DateTime);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EnabledManualAssign", entity.EnabledManualAssign, DbType.Boolean);
            parameters.Add("?ManualAssignWaitTime", entity.ManualAssignWaitTime, DbType.Int32, size: 11);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
            parameters.Add("?DepartmentName", entity.DepartmentName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?WorkingCompanyName", entity.WorkingCompanyName?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkingCompanyEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除劳务公司
        public async Task<bool> Delete(long workingCompanyId)
        {
            string sql = @"DELETE FROM workingcompany WHERE WorkingCompanyId=?WorkingCompanyId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkingCompanyId", workingCompanyId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取劳务公司
        public async Task<WorkingCompanyEntity> GetEntity(long workingCompanyId)
        {
            string sql = string.Format(@"{0} WHERE WorkingCompanyId=?WorkingCompanyId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkingCompanyId", workingCompanyId, DbType.Int64);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkingCompanyEntity>(sql, parameters);
        }
        #endregion

        #region 获取劳务公司列表
        public async Task<IEnumerable<WorkingCompanyEntity>> GetOnlyList(int? companyId, long? departmentId, string workingCompanyName)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (companyId.HasValue)
            {
                wheres.Add("CompanyId=?CompanyId");
                parameters.Add("?CompanyId", companyId, DbType.Int32);
            }
            if (departmentId.HasValue)
            {
                wheres.Add("DepartmentId=?DepartmentId");
                parameters.Add("?DepartmentId", departmentId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(workingCompanyName))
            {
                wheres.Add("WorkingCompanyName LIKE ?WorkingCompanyName");
                parameters.Add("?WorkingCompanyName", $"%{workingCompanyName}%", DbType.AnsiString);
            }
            string sql = wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "";
            sql = QUERY + sql;
            return await this.databaseContext.Slave.QueryAsync<WorkingCompanyEntity>(sql, parameters);
        }
        #endregion

        #region 获取劳务公司分页
        public async Task<(IEnumerable<WorkingCompanyEntity>, int)> Query(int? companyId, long? departmentId, string workingCompanyName, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (companyId.HasValue)
            {
                wheres.Add("CompanyId=?CompanyId");
                parameters.Add("?CompanyId", companyId, DbType.Int32);
            }
            if (departmentId.HasValue)
            {
                wheres.Add("DepartmentId=?DepartmentId");
                parameters.Add("?DepartmentId", departmentId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(workingCompanyName))
            {
                wheres.Add("WorkingCompanyName LIKE ?WorkingCompanyName");
                parameters.Add("?WorkingCompanyName", $"%{workingCompanyName}%", DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM workingcompany {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<WorkingCompanyEntity, int>(sql, parameters);
        }


        #endregion

        #region 根据区县编码获取劳务公司列表
        public async Task<IEnumerable<WorkingCompanyEntity>> GetListByCountyCode(string countyCode)
        {
            string sql = @"SELECT A.WorkingCompanyId,A.UpdateTime,A.EditAdminId,A.EditAdminName,A.EnabledManualAssign,A.ManualAssignWaitTime,A.CompanyId,A.CompanyName,
						  A.DepartmentId,A.DepartmentName,A.WorkingCompanyName,A.CreateTime,A.CreateAdminId,A.CreateAdminName 
						  FROM WorkingCompany A INNER JOIN  AgentRecord B ON A.CompanyId=B.CompanyId INNER JOIN AgentAreaRecord C ON C.AgentRecordId=B.AgentRecordId WHERE C.CountyCode=?CountyCode; ";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CountyCode", countyCode.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.QueryAsync<WorkingCompanyEntity>(sql, parameters);
        }
        #endregion
    }
}



